package model;

import java.util.ArrayList;

import java.util.List;
import java.util.Random;

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

/**
* Title: MyHandler.java<br>
* Description: class for XML parser, extends DefaultHandler<br>
* Created: 05.01.2013<br>
* Copyright: Copyright (c) 2012<br>
* Company: Luxoft Corporation
* @author Sveta
* @version $Rev$: , $Date$: , $Author$:
*/
public class MyHandler extends DefaultHandler {
	boolean name, productionCountry, weight, price, nameB, idB, Product, bk;
	Product prod;
	Bucket buk = new Bucket();
	private ArrayList<Bucket> buk1;
	//public static ArrayList<Product> prod1 = new ArrayList<Product>();
	private String s;
	Random rand = new Random();
	
	public MyHandler(){
		super();
		buk1 = new ArrayList<Bucket>();
	}
	
	public List<Bucket> getResultOfParsing(){
		return buk1;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) {

		if (qName.equals("Bucket")) {
			bk = true;
			buk.setId(rand.nextInt());
		} else if ((qName.equals("name")) && (bk)) {
			nameB = true;
			bk = false;

		} else

		if (qName.equals("name")) {
			name = true;
			prod = new Product();
		} else

		if (qName.equals("productionCountry")) {

			productionCountry = true;
		} else if (qName.equals("weight")) {

			weight = true;
		} else if (qName.equals("price")) {

			price = true;
		}

	}

	@Override
	public void characters(char ch[], int start, int length) {
		s = new String(ch, start, length);

	}

	@Override
	public void endElement(String uri, String localName, String qName) {
		if (nameB) {
			buk.setName(s);
			nameB = false;
		} else if (name) {
			prod.setName(s);
			name = false;
		} else if (productionCountry) {
			prod.setProductionCountry(s);
			productionCountry = false;
		} else if (weight) {
			prod.setWeight(Integer.parseInt(s));

			weight = false;
		} else if (price) {

			prod.setPrice(Integer.parseInt(s));
			price = false;
		} else

		if (qName.equals("Product")) {

			prod.setBucketId(buk.getId());
			int temp;
			do {
				temp = rand.nextInt();

			} while (temp == buk.getId());
			prod.setId(temp);
			buk.add(prod);
			Product = false;
			//prod1.add(prod);
		} else if (qName.equals("Bucket")) {

			//buk.PrintBucket();

			buk1.add(buk);
		}
	}
}
